<?php
require_once('../models/authorization.php');
require_once('../models/post.php');
require_once('category_controller.php');
require_once('post_controller.php');
require_once('../includes/smarty/libs/Smarty.class.php'); 
require_once('../const.php');

/**
 * Responsible for rendering the new.php view
 * and handling requests.
 * 
 * @author Matt Makins
 * 
 */
class NewPostRenderer{

	private $smarty;
	private $session;
	private $category_controller;
	private $post_controller;
		
	public function NewPostRenderer(){
		
		$this->session = new Authorization();
		$this->smarty = new Smarty();
		$this->category_controller = new CategoryController();
		$this->post_controller = new PostController();
		
		if(! $this->session->checkLogin())
			header('Location: error.php?error=authorization');

		if($_POST['do'] == "update")
			$this->editPost();
		else if($_REQUEST['do'] == "edit")
			$this->getEditPlaceHolderValues();		
		else
			$this->addPost();				

		$this->getPlaceHolderValues();
		$this->renderPage();
	}
	
	private function editPost(){
		
		$this->post_controller->editPost($_POST['title'], $_POST['entry'], $_POST['category'],
			$_POST['id'], $_POST['comments']);	
	}

	private function addPost(){
		
		if(isset($_POST['entry'])){

			require_once('post_controller.php');
			$post = new PostController();
			$post->addPost($_POST['title'], $_POST['entry'], $_POST['category'], $_POST['comments']);
		}
	}

	private function getEditPlaceHolderValues(){
		
		$id = $_REQUEST['id']; 
		$p = $this->post_controller->getPostById($id);

		$this->smarty->assign("title_value", $p->getTitle());
		$this->smarty->assign("category_value", $p->getCategoryId());
		$this->smarty->assign("article_value", $p->getEntry());
		$this->smarty->assign("id", $p->getId());
		$this->smarty->assign("do_value", "update");
	}

	const PAGE_TITLE_PLACEHOLDER_NAME = "title"; 

	const LOGGED_IN_PLACEHOLDER_NAME = "loggedIn";
	
	const CATEGORY_ID_PLACEHOLDER_NAME = "category_id";
	
	const USERNAME_PLACEHOLDER_NAME = "username";

	const CATEGORY_NAME_PLACEHOLDER_NAME = "category_name";
	
	private function getPlaceHolderValues(){
		
		$this->smarty->assign(self::PAGE_TITLE_PLACEHOLDER_NAME, BLOG_NAME . ": New Post");
		$this->smarty->assign(self::LOGGED_IN_PLACEHOLDER_NAME, $this->session->checkLogin());
		$this->smarty->assign(self::CATEGORY_ID_PLACEHOLDER_NAME, $this->category_controller->getAllCategoryIds());
		$this->smarty->assign(self::CATEGORY_NAME_PLACEHOLDER_NAME, $this->category_controller->getAllCategoryNames());
		$this->smarty->assign("errorsPresent", Post::getNumberOfErrors() > 0); 
		$this->smarty->assign("numberOfErrors", Post::getNumberOfErrors());
		$this->smarty->assign("errors", Post::getErrors());
		$this->smarty->assign(self::USERNAME_PLACEHOLDER_NAME, $this->session->getUsername());
	}
	
	const TEMPLATE_NAME = "new.tpl";
	
	private function renderPage(){

		$this->smarty->display(self::TEMPLATE_NAME);
	}
}
$newPost = new NewPostRenderer();
?>